import { FIRELOW } from './helper';
import { TIME_24, TIME_96 } from '@/pages/ETrade/components/helper';
// 保留几位小数
export const NumberFormat = (value, precision) => {
  const newNum = Math.round(value * precision) / precision;
  return newNum;
};

export const getXaxis = (data, name) => {
  const newValue = [];
  data?.map((item) => {
    newValue.push(item[name]);
  });
  return newValue;
};

// 主页面取数逻辑
export const getTargetData = (data, name, echarsData) => {
  data.map((item) => {
    if (item?.children?.length) {
      if (item.name === name) {
        echarsData.push(...item.children);
      } else {
        getTargetData(item.children, name, echarsData);
      }
    } else {
      if (item.name === name) {
        echarsData.push(item);
      }
    }
  });
};

// 96点取数逻辑
export const getTargetData96 = (params, echarsData) => {
  const { data, name, date, otherTradingUnit, flag, is96TradingUnit } = params;
  data.map((item) => {
    if (name === item.name) {
      echarsData.push(item);
    }
    if (item?.children && item?.children.length) {
      item?.children.map((y) => {
        if (name === y.name && flag === y.flag) {
          if (otherTradingUnit) {
            if (y?.children && y?.children.length) {
              echarsData.push(...y?.children);
            }
          } else {
            echarsData.push(y);
          }
        }
        if (name === y.name && flag === '合计__son') {
          echarsData.push(y);
        }
        if (name === y.name && is96TradingUnit && flag !== y.flag) {
          echarsData.push(y);
        }
        if (y?.children && y?.children.length) {
          y?.children.map((z) => {
            if (name === z.name && date && date === z.data.date) {
              echarsData.push(z);
            }
          });
        }
      });
    }
  });
};

// 格式化名称
export const formatName = (data) => {
  if (data.split('-').length && data.split('-').length > 1) {
    return data.split('-').join('');
  }
  return data;
};

// 表格数据添加标志
export const getFlagDataSource = (dataSource, postdata) => {
  dataSource.map((item) => {
    // 96/24点展示对应值
    if (dataSource.length === 97 && postdata.dimension === 'ns' && item.name !== '合计') {
      item.name = TIME_96[item.name - 1].split(':').join('');
    }
    if (dataSource.length === 25 && postdata.dimension === 'ns' && item.name !== '合计') {
      item.name = TIME_24[item.name - 1].split(':').join('');
    }
    item.flag = `${item.name}__parent`;
    item.crumbsName = formatName(item.name); // 添加面包屑
    (item?.children || []).map((y) => {
      y.flag = `${item.name}__son`;
      y.crumbsName = `${formatName(item.name)}——${formatName(y.name)}`; // 添加面包屑
      y.code = y.code ?? item.code;
      y.date = y.date ?? item?.data?.date;
      (y?.children || []).map((z) => {
        z.flag = `${item.name}__grandson`;
        if (y?.children.length === 96) {
          z.name = TIME_96[z.name - 1].split(':').join('');
        } else {
          z.name = TIME_24[z.name - 1].split(':').join('');
        }
        z.crumbsName = `${formatName(item.name)}——${formatName(y.name)}——${formatName(z.name)}`; // 添加面包屑
      });
    });
  });
  return dataSource;
};

// 格式化导出数据
export const formatJson = (filterVal, jsonData) => {
  return jsonData.map((v) => {
    return filterVal.map((j) => {
      if (v && v.data && v.data[j]) {
        return v.data[j];
      } else if (j === 'name') {
        return formatName(v[j]); // 导出表格第一列
      } else {
        return '-';
      }
    });
  });
};
// 根据名称拿指定数据
export const forMater = (data, name) => {
  const newValue = [];
  data.map((item) => {
    if (item.data) {
      newValue.push(item.data[name] === null ? '' : item.data[name]);
    } else {
      newValue.push('');
    }
  });
  return newValue;
};

// 计算指定参数之和
export const getEcharsData96 = (data, name, toFixedThree) => {
  const echartsValues = [];
  const tofix = toFixedThree ? 1000 : 100; // 保留几位小数 1000-3位  100-两位
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      if (echartsValues[index] || echartsValues[index] === 0) {
        const result = Number(echartsValues[index]) + Number(y.data[name]);
        echartsValues[index] = NumberFormat(result, tofix);
      } else {
        echartsValues.push(
          y.data === null || y.data[name] === null
            ? null
            : NumberFormat(Number(y.data[name]), tofix),
        );
      }
    });
  });
  return echartsValues;
};
// 计算基数分配比例
export const getGridBaseRatio = (data) => {
  const gridBaseRatio = [];
  const gridBaseRatioObj = {};
  const maxGridBaseRatio = [];
  const minGridBaseRatio = [];
  if (data?.length === 1) {
    data.map((item) => {
      (item?.children || []).map((y) => {
        gridBaseRatio.push(
          y.data.gridBaseRatio === null || y.data === null ? null : Number(y.data.gridBaseRatio),
        );
      });
    });
    return gridBaseRatio;
  } else {
    data.map((item) => {
      (item?.children || []).map((y, index) => {
        if (maxGridBaseRatio[index] || maxGridBaseRatio[index] === 0) {
          if (maxGridBaseRatio[index] < Number(y.data.gridBaseRatio)) {
            maxGridBaseRatio[index] = Number(y.data.gridBaseRatio);
          }
        } else {
          // maxGridBaseRatio.push(Number(y.data.gridBaseRatio));
          maxGridBaseRatio.push(
            y.data.gridBaseRatio === null || y.data === null ? null : Number(y.data.gridBaseRatio),
          );
        }
        if (minGridBaseRatio[index] || minGridBaseRatio[index] === 0) {
          if (minGridBaseRatio[index] > Number(y.data.gridBaseRatio)) {
            minGridBaseRatio[index] = Number(y.data.gridBaseRatio);
          }
        } else {
          // minGridBaseRatio.push(Number(y.data.gridBaseRatio));
          minGridBaseRatio.push(
            y.data.gridBaseRatio === null || y.data === null ? null : Number(y.data.gridBaseRatio),
          );
        }
      });
    });
    gridBaseRatioObj.maxGridBaseRatio = maxGridBaseRatio;
    gridBaseRatioObj.minGridBaseRatio = minGridBaseRatio;
    return gridBaseRatioObj;
  }
};
// 计算日前结算电价
export const getProvincialDayaheadStatementPrice96 = (data) => {
  const echartsValues = [];
  const provincialDayaheadStatementIncome = [];
  const provincialDayaheadStatementQuantity = [];
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      let income = y.data.provincialDayaheadStatementIncome;
      let quantity = y.data.provincialDayaheadStatementQuantity;
      if (
        provincialDayaheadStatementIncome[index] ||
        provincialDayaheadStatementIncome[index] === 0
      ) {
        provincialDayaheadStatementIncome[index] =
          Number(provincialDayaheadStatementIncome[index]) + Number(income);
      } else {
        provincialDayaheadStatementIncome.push(income);
      }
      if (
        provincialDayaheadStatementQuantity[index] ||
        provincialDayaheadStatementQuantity[index] === 0
      ) {
        provincialDayaheadStatementQuantity[index] =
          Number(provincialDayaheadStatementQuantity[index]) + Number(quantity);
      } else {
        provincialDayaheadStatementQuantity.push(quantity);
      }
    });
  });
  provincialDayaheadStatementIncome.map((item, index) => {
    let result = 0;
    if (provincialDayaheadStatementQuantity[index] != 0) {
      result = item / provincialDayaheadStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算实时结算电价
export const getProvincialRealtimeStatementPrice96 = (data) => {
  const echartsValues = [];
  const provincialRealtimeStatementIncome = [];
  const provincialRealtimeStatementQuantity = [];
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      let income = y.data.provincialRealtimeStatementIncome;
      let quantity = y.data.provincialRealtimeStatementQuantity;
      if (
        provincialRealtimeStatementIncome[index] ||
        provincialRealtimeStatementIncome[index] === 0
      ) {
        provincialRealtimeStatementIncome[index] =
          Number(provincialRealtimeStatementIncome[index]) + Number(income);
      } else {
        provincialRealtimeStatementIncome.push(income);
      }
      if (
        provincialRealtimeStatementQuantity[index] ||
        provincialRealtimeStatementIncome[index] === 0
      ) {
        provincialRealtimeStatementQuantity[index] =
          Number(provincialRealtimeStatementQuantity[index]) + Number(quantity);
      } else {
        provincialRealtimeStatementQuantity.push(quantity);
      }
    });
  });
  provincialRealtimeStatementIncome.map((item, index) => {
    let result = 0;
    if (provincialRealtimeStatementQuantity[index] != 0) {
      result = item / provincialRealtimeStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算过渡电价
export const getTransitionPrice96 = (data, price) => {
  const echartsValues = [];
  const baseQuantity = [];
  const provincialDayaheadClearingQuantity = [];
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      let income = y.data.baseQuantity;
      let quantity = y.data.provincialDayaheadClearingQuantity;
      if (baseQuantity[index] || baseQuantity[index] === 0) {
        baseQuantity[index] = Number(baseQuantity[index]) + Number(income);
      } else {
        baseQuantity.push(income);
      }
      if (
        provincialDayaheadClearingQuantity[index] ||
        provincialDayaheadClearingQuantity[index] === 0
      ) {
        provincialDayaheadClearingQuantity[index] =
          Number(provincialDayaheadClearingQuantity[index]) + Number(quantity);
      } else {
        provincialDayaheadClearingQuantity.push(quantity);
      }
    });
  });
  baseQuantity.map((item, index) => {
    let result = 0;
    if (provincialDayaheadClearingQuantity[index] != 0) {
      result = item / provincialDayaheadClearingQuantity[index];
    }
    const kValue = NumberFormat(result, 100);
    const transitionPrice = kValue * 332 + (1 - kValue) * Number(price[index]);
    echartsValues.push(NumberFormat(transitionPrice, 100));
  });

  return echartsValues;
};

// 计算综合电价
export const getTotalStatementPrice = (data) => {
  const echartsValues = [];
  const totalStatementEnergyIncome = getEcharsData96(data, 'totalStatementEnergyIncome'); // 综合电费之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementQuantity'); // 综合电量之和
  totalStatementEnergyIncome.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result = item / totalStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
//甘肃 计算综合电价
export const getTotalStatementPrice_gansu = (data) => {
  const echartsValues = [];
  const totalStatementEnergyIncome = getEcharsData96(data, 'totalStatementEnergyIncome'); // 综合电费之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementEnergyQuantity'); // 综合电量之和
  totalStatementEnergyIncome.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result = item / totalStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算综合电价的平均电价
export const getTotalStatementEnergyPrice = (data) => {
  const echartsValues = [];
  let totalStatementEnergyIncome = 0;
  data.map((item) => {
    totalStatementEnergyIncome += Number(item);
  });

  data.map(() => {
    const result = totalStatementEnergyIncome / data.length;
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算算术均价
export const _getTotalStatementEnergyPrice = (data, name) => {
  const echartsValues = [];
  const newData = []; // 过滤有综合电价的数据
  let totalStatementEnergyIncome = 0;
  data.map((item) => {
    if (item.data && item.data[name]) {
      newData.push(item);
    }
  });
  newData.map((item) => {
    totalStatementEnergyIncome += Number(item.data[name]);
  });

  data.map((v) => {
    const result = totalStatementEnergyIncome / newData.length;
    echartsValues.push(
      v?.data?.provincialRealtimeClearingQuantity &&
        v?.data?.provincialRealtimeClearingQuantity !== '0.00'
        ? NumberFormat(result, 100)
        : '-',
    );
  });
  return echartsValues;
};

// 计算现货电量比例
export const getPercentageSpotElectricity = (data) => {
  const echartsValues = [];
  const provincialDayaheadStatementQuantity = getEcharsData96(
    data,
    'provincialDayaheadStatementQuantity',
  ); // 日前电量之和
  const provincialRealtimeStatementQuantity = getEcharsData96(
    data,
    'provincialRealtimeStatementQuantity',
  ); // 实时电量之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementQuantity'); // 综合电量之和
  provincialDayaheadStatementQuantity.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result = (item + provincialRealtimeStatementQuantity[index]) / totalStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算现货综合电价
export const getSpotElectricityPeice = (data) => {
  const echartsValues = [];
  const provincialDayaheadStatementIncome = getEcharsData96(
    data,
    'provincialDayaheadStatementIncome',
  ); // 日前电费之和
  const provincialRealtimeStatementIncome = getEcharsData96(
    data,
    'provincialRealtimeStatementIncome',
  ); // 实时电费之和
  const provincialDayaheadStatementQuantity = getEcharsData96(
    data,
    'provincialDayaheadStatementQuantity',
  ); // 日前电量之和
  const provincialRealtimeStatementQuantity = getEcharsData96(
    data,
    'provincialRealtimeStatementQuantity',
  ); // 实时电量之和
  provincialDayaheadStatementIncome.map((item, index) => {
    let result = 0;
    if (
      provincialDayaheadStatementQuantity[index] + provincialRealtimeStatementQuantity[index] !==
      0
    ) {
      result =
        (item + provincialRealtimeStatementIncome[index]) /
        (provincialDayaheadStatementQuantity[index] + provincialRealtimeStatementQuantity[index]);
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算中长期价差
export const getMediumAndLongTermSpread = (data) => {
  const echartsValues = [];
  const totalLongTermStatementEnergyIncome = getEcharsData96(
    data,
    'totalLongTermStatementEnergyIncome',
  ); // 中长期电费之和
  const totalLongTermStatementQuantity = getEcharsData96(data, 'totalLongTermStatementQuantity'); // 中长期电量之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementQuantity'); // 综合电量之和
  totalLongTermStatementEnergyIncome.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result =
        (item - totalLongTermStatementQuantity[index] * FIRELOW) / totalStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算现货价差
export const getSpotPrice = (data) => {
  const echartsValues = [];
  const provincialRealtimeStatementIncome = getEcharsData96(
    data,
    'provincialRealtimeStatementIncome',
  ); // 实时电费之和
  const provincialDayaheadStatementIncome = getEcharsData96(
    data,
    'provincialDayaheadStatementIncome',
  ); // 日前电费之和
  const provincialDayaheadStatementQuantity = getEcharsData96(
    data,
    'provincialDayaheadStatementQuantity',
  ); // 日前电量之和
  const provincialRealtimeStatementQuantity = getEcharsData96(
    data,
    'provincialRealtimeStatementQuantity',
  ); // 实时电量之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementQuantity'); // 综合电量之和
  provincialRealtimeStatementIncome.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result =
        (item +
          provincialDayaheadStatementIncome[index] -
          (provincialDayaheadStatementQuantity[index] +
            provincialRealtimeStatementQuantity[index]) *
            FIRELOW) /
        totalStatementQuantity[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算度电价差
export const getDegreePrice = (data) => {
  const echartsValues = [];
  const totalStatementEnergyIncome = getEcharsData96(data, 'totalStatementEnergyIncome'); // 综合电费之和
  const totalStatementQuantity = getEcharsData96(data, 'totalStatementQuantity'); // 综合电量之和
  totalStatementEnergyIncome.map((item, index) => {
    let result = 0;
    if (totalStatementQuantity[index] !== 0) {
      result = item / totalStatementQuantity[index] - FIRELOW;
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};
// 计算两数之和相除
export const getPowerForecastPrice = (data, denominatorName, molecularName) => {
  const echartsValues = [];
  const denominatorNameAdd = getEcharsData96(data, denominatorName); // 分母参数之和
  const molecularNameAdd = getEcharsData96(data, molecularName); // 分子参数之和
  denominatorNameAdd.map((item, index) => {
    let result = 0;
    if (molecularNameAdd[index] !== 0) {
      result = item / molecularNameAdd[index];
    }
    echartsValues.push(NumberFormat(result, 100));
  });
  return echartsValues;
};

// 计算96点正负电费
export const getEcharsData96_Icome = (data, quantityName, priceName, toFixedThree) => {
  const echartsValues = [];
  const tofix = toFixedThree ? 1000 : 100; // 保留几位小数 1000-3位  100-两位
  data.map((item) => {
    (item?.children || []).map((y, index) => {
      if (echartsValues[index] || echartsValues[index] === 0) {
        const result =
          Number(echartsValues[index]) +
          NumberFormat(Number(y.data[quantityName]) * Number(y.data[priceName]), tofix);
        echartsValues[index] = NumberFormat(result, tofix);
      } else {
        echartsValues.push(
          y.data === null || y.data[quantityName] === null || y.data[priceName] === null
            ? null
            : NumberFormat(Number(y.data[quantityName]) * Number(y.data[priceName]), tofix),
        );
      }
    });
  });
  return echartsValues;
};
// 计算正负电价
export const getCorrectNegativePrice = (data, quantityName, priceName) => {
  const echartsValues = [];
  const income = getEcharsData96_Icome(data, quantityName, priceName); // 电费
  const quantity = getEcharsData96(data, quantityName); // 电量

  income.map((item, index) => {
    let result;
    if (!!quantity[index]) {
      result = NumberFormat(item / quantity[index], 100);
    }
    echartsValues.push(result);
  });
  return echartsValues;
};

//子页面处理数据方法选择
export const dealDataChoose = (funcName, ...key) => {
  const map = {
    forMater,
    getEcharsData96,
    getTotalStatementPrice_gansu,
    getTotalStatementEnergyPrice,
    _getTotalStatementEnergyPrice,
    getPowerForecastPrice,
    getCorrectNegativePrice,
    getProvincialDayaheadStatementPrice96,
    getDegreePrice,
    getSpotPrice,
    getMediumAndLongTermSpread,
    getSpotElectricityPeice,
    getPercentageSpotElectricity,
    getGridBaseRatio,
    getProvincialRealtimeStatementPrice96,
    getTransitionPrice96,
    getTotalStatementPrice,
  };
  return map[funcName](...key);
};

//表格选中图表数据
export const chooseData = (data, value, dimensionEnum, hasUrlData) => {
  const { name, flag, date } = value;
  let isSDN = false; // 判断是否是场站-日期-96/24点数据
  let echarsData = [];
  let XAXIS;
  /***主页面***/
  if (!hasUrlData) {
    switch (flag) {
      case `合计__parent`:
        echarsData = data.slice(1);
        XAXIS = getXaxis(echarsData, 'name');
        break;
      case `合计__son`: {
        // 合计下的日期
        const newData = data.slice(1) || [];
        getTargetData(newData, name, echarsData);
        XAXIS = getXaxis(echarsData, 'flag').map((item) => {
          return item.split('__')[0];
        });
        break;
      }
      case `${name}__parent`: {
        // 其他交易单元
        const newData = data.slice(1) || [];
        getTargetData(newData, name, echarsData);
        XAXIS = getXaxis(echarsData, 'name');
      }
    }
  } else {
    /***子页面***/
    if (flag === `合计__parent`) {
      echarsData = data.slice(1);
      XAXIS = getXaxis(echarsData, 'name');
    }
    // 合计下的日期
    else if (flag === `合计__son`) {
      const newData = data.slice(1) || [];
      getTargetData96({ data: newData, name, flag }, echarsData);
      XAXIS = getXaxis(echarsData, 'flag').map((item) => {
        return item.split('__')[0];
      });
    }
    // 合计下的日期下的96点
    else if (flag === `合计__grandson`) {
      const newData = data.slice(1) || [];
      getTargetData96({ data: newData, name, flag, date }, echarsData);
      XAXIS = getXaxis(echarsData, 'flag').map((item) => {
        return item.split('__')[0];
      });
    } else if (flag === `${name}__parent`) {
      if (dimensionEnum) {
        // 96点
        const newData = data.slice(1) || [];
        getTargetData96({ data: newData, name, flag, otherTradingUnit: true }, echarsData);
        XAXIS = getXaxis(echarsData[0]?.children, 'name');
        echarsData = echarsData[0]?.children;
      } else {
        // 其他交易单元
        const newData = data.slice(1) || [];
        getTargetData96({ data: newData, name }, echarsData);
        isSDN = true;
        XAXIS = getXaxis(echarsData[0]?.children[0]?.children, 'name');
      }
    } else if (flag && flag.split('__')[1] === `son`) {
      if (dimensionEnum) {
        // 96点下的交易单元
        const newData = data.slice(1) || [];
        getTargetData96({ data: newData, name, flag, is96TradingUnit: true }, echarsData);
        XAXIS = getXaxis(newData, 'name');
      } else {
        // 其他交易单元下的日期
        const newData = data.slice(1) || [];
        getTargetData96({ data: newData, name, flag, otherTradingUnit: true }, echarsData);
        XAXIS = getXaxis(echarsData, 'name');
      }
    }
  }
  return {
    echarsData,
    XAXIS,
    isSDN,
  };
};
